//
//  WBOAuthViewController.swift
//  微博
//
//  Created by 康智桐 on 2018/4/15.
//  Copyright © 2018年 Kk. All rights reserved.
//

import UIKit
import SVProgressHUD


//通过webview 加载新浪微博授权页面控制器
class WBOAuthViewController: UIViewController {
    
    
    
    lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        
        view.backgroundColor = UIColor.white
        //取消滚动视图
        webView.scrollView.isScrollEnabled = false
        
        //设置代理
        webView.delegate = self
        
        
        //设置导航栏
        title = "登录新浪微博"
        
        //设置导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        
        
        
    }
    
    

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        //加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        //确定要访问的资源
        guard let url = URL(string: urlString)
             else {
            return
        }
        //建立请求
        let request = URLRequest(url:url)
        
        //加载请求
        webView.loadRequest(request)
        
        
        
        
    }

 //监听方法
    @objc func close(){
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
        
        
    }
    
    
}

extension WBOAuthViewController:UIWebViewDelegate{
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //如果请求地址包含 baidu 不加载页面，否则加载
        
        if request.url?.absoluteString.hasPrefix(WBRedirectURI) == false {
            
            return true
        }

        //从回调地址中查找字符串 ‘code=’
        //如果有 授权成功，没有则授权失败
        //print("加载请求----------\(request.url?.absoluteString)")
        
        //print("加载请求---\(request.url?.query)")
        
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            
            //回到上一级页面
            close()
            return false
        }
        
        
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        
        print("授权码 - \(code)")
        //使用授权码获取token
        WBNetworkManager.shared.loadAccessToken(code: code){ (isSuccess) in
            
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            }else{
                SVProgressHUD.showInfo(withStatus: "登录成功")
                //跳转界面 通过通知跳转，发送登录成功消息
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
                
                //关闭窗口
                self.close()
                
            }
            
            print("")
            
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
